package web_http

import(
	"log"
	"time"
	"io/ioutil"
	"fmt"
	"net/http"
	"encoding/json"
)


// 1.系统健康检查
func CheckServerHealth(baseURL string) (bool, error) {
	url := baseURL + "/health"
	log.Printf("健康检查请求: %s", url)
	
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		return false, fmt.Errorf("健康检查请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取完整响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false, fmt.Errorf("读取响应失败: %v", err)
	}

	log.Printf("健康检查响应 - 状态码: %d, 响应体: %s", resp.StatusCode, string(body))

	if resp.StatusCode != http.StatusOK {
		return false, fmt.Errorf("服务器返回状态: %d, 响应: %s", resp.StatusCode, string(body))
	}

	var result struct {
		Status string `json:"status"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return false, fmt.Errorf("解析响应失败: %v, 原始响应: %s", err, string(body))
	}

	log.Printf("健康检查解析结果: status=%s", result.Status)
	return result.Status == "ok", nil
}

// 2.系统就绪检查
func CheckServerReadiness(baseURL string) (bool, error) {
	url := baseURL + "/ready"
	log.Printf("就绪检查请求: %s", url)
	
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		return false, fmt.Errorf("就绪检查请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取完整响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false, fmt.Errorf("读取响应失败: %v", err)
	}

	log.Printf("就绪检查响应 - 状态码: %d, 响应体: %s", resp.StatusCode, string(body))

	if resp.StatusCode != http.StatusOK {
		return false, fmt.Errorf("服务器返回状态: %d, 响应: %s", resp.StatusCode, string(body))
	}

	var result struct {
		Status string `json:"status"`
		Checks map[string]string `json:"checks,omitempty"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return false, fmt.Errorf("解析响应失败: %v, 原始响应: %s", err, string(body))
	}

	log.Printf("就绪检查解析结果: status=%s, checks=%v", result.Status, result.Checks)
	return result.Status == "ready", nil
}


